package controller

import (
	"net/http"

	"gitee.com/chuanjinge/gopkgserv/api/request"
	"gitee.com/chuanjinge/gopkgserv/api/response"
	"gitee.com/chuanjinge/gopkgserv/config"
	"gitee.com/chuanjinge/gopkgserv/internal/service"
	"gitee.com/chuanjinge/gopkgserv/pkg/auth"
	"gitee.com/chuanjinge/gopkgserv/pkg/wechat"

	"github.com/gin-gonic/gin"
)

// LoginController 控制器
type LoginController struct{}

// CheckToken 方法，校验 JWT token（POST JSON 接收 token）
func (lc *LoginController) CheckToken(c *gin.Context) {
	type TokenRequest struct {
		Token string `json:"token" binding:"required"`
	}
	var req TokenRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "token参数不能为空"})
		return
	}
	_, err := auth.ParseToken(req.Token)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, response.Success(nil))
}

// login 方法，处理登录请求
func (lc *LoginController) Login(c *gin.Context) {
	req, err := request.BindAndValidateLoginParam(c)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
		return
	}
	// 这里可以添加登录逻辑
	// 1. 使用 req.Code 调用微信接口获取 session_key 和 openid
	phoneNumber, err := wechat.GetPhoneNumber(config.WeChatMiniAppAppID, config.WeChatMiniAppAppSecret, req.Code)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"msg": err.Error()})
		return
	}
	// 2. 根据 phoneNumber 查找或创建用户
	service := &service.UserService{}
	_, err = service.LoginByMobile(phoneNumber)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"msg": err.Error()})
		return
	}
	// 3. 生成并返回 JWT 或其他形式的登录凭证
	// 假设 service.LoginByMobile 返回 token 字符串
	userDao, err := service.LoginByMobile(phoneNumber)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"msg": err.Error()})
		return
	}
	resp := response.LoginResponse{Token: userDao.AccessToken}
	c.JSON(http.StatusOK, response.Success(resp))
}
